#!/usr/bin/env python

"""Reads an OPML file, gets all feeds in it and writes Blosxom entries
corresponding to the items in the feeds."""

import os
import sys
import getopt
import signal

from plagglib import plagg


def usage(rc):
    print "Usage: plagg [-fFnhoVv] [-d newsdir] [-t timeout] [opmlfile [nickname ...]]]"
    sys.exit(rc)

path = os.path.join(os.getenv('HOME'), 'bblog', 'news')
news = verbose = timeout = feed = old_entries = 0
footer = 1
try:
    opts, args = getopt.getopt(sys.argv[1:], 'd:fFnhoVvt:')
except getopt.GetoptError, e:
    print e
    usage(3)
for o, v in opts:
    if o == '-d':
        path = v
    elif o == '-F':
        feed = 1
    elif o == '-f':
        footer = 0
    elif o == '-n':
        news = 1
    elif o == '-h':
        usage(0)
    elif o == '-o':
        old_entries = 1
    elif o == '-V':
        print plagg.__version__
        sys.exit(0)
    elif o == '-v':
        verbose += 1
    elif o == '-t':
        timeout = int(v)

if timeout and hasattr(signal, 'alarm'):
    signal.signal(signal.SIGALRM, signal.default_int_handler)
    signal.alarm(timeout)

argc = len(args)
if feed and argc != 2:
    print "Usage: plagg -F feed-url nickname"
    sys.exit(3)
if argc == 0:
    plagg = plagg.Plagg(os.path.join(path, 'news.opml'))
elif argc == 1:
    plagg = plagg.Plagg(args[0])
elif argc >= 2:
    old_entries = 1
    plagg = plagg.Plagg(args[0], args[1:])
else:
    usage(3)

plagg.setConfig(path, verbose, footer, old_entries)
try:
    if feed:
        plagg.singleFeed(args[0], args[1])
    else:
        plagg.startOPML()
except KeyboardInterrupt:
    pass
if news:
    plagg.newEntries()

sys.exit(plagg.errors and 1 or 0)
